<template>
  <div class="user-profile">
    <el-card class="box-card">
      <div slot="header">
        <span>个人资料</span>
        <button-box style="float: right; padding: 3px 0" type="text" text="编辑" @click="handleEditInfo"></button-box>
      </div>
      <div class="user-info">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar"></el-avatar>
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              action="/api/upload/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :on-progress="handleAvatarProgress"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
              :auto-upload="false"
              ref="avatarUpload">
              <button-box 
                type="primary" 
                text="选择头像" 
                size="mini"
                :loading="avatarUploading">
              </button-box>
            </el-upload>
            <div v-if="avatarUploadProgress > 0 && avatarUploadProgress < 100" class="upload-progress">
              <el-progress :percentage="avatarUploadProgress" :stroke-width="2"></el-progress>
            </div>
          </div>
        </div>
        <div class="info-container">
          <div class="info-item">
            <span class="label">用户名：</span>
            <span class="value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">姓名：</span>
            <span class="value">{{ userInfo.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">邮箱：</span>
            <span class="value">{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号：</span>
            <span class="value">{{ userInfo.phone || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">角色：</span>
            <span class="value">
              <el-tag v-for="role in userInfo.roles" :key="role" size="small" style="margin-right: 5px">{{ role }}</el-tag>
            </span>
          </div>
          <div class="info-item">
            <span class="label">个人标签：</span>
            <span class="value">
              <el-tag 
                v-for="(tag, index) in userInfo.tags" 
                :key="index" 
                size="small" 
                :type="tagTypes[index % tagTypes.length]"
                style="margin-right: 5px; margin-bottom: 5px">
                {{ tag }}
              </el-tag>
              <span v-if="!userInfo.tags || userInfo.tags.length === 0" class="text-muted">未设置</span>
            </span>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="box-card" v-if="canChangePassword">
      <div slot="header">
        <span>修改密码</span>
      </div>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <el-form-item>
          <button-box type="primary" text="保存" @click="handleChangePassword"></button-box>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- <el-card class="box-card" v-else>
      <div class="no-permission">
        <i class="el-icon-lock"></i>
        <p>您没有修改密码的权限，请联系管理员。</p>
      </div>
    </el-card> -->

    <!-- 头像预览对话框 -->
    <dialog-box
      title="头像预览"
      :visible.sync="avatarPreviewVisible"
      width="400px"
      @confirm="confirmAvatarUpload"
      @cancel="cancelAvatarUpload"
    >
      <div class="avatar-preview-container">
        <div class="preview-image">
          <img :src="previewAvatarUrl" alt="头像预览" />
        </div>
        <div class="preview-tips">
          <p>请确认要上传这张头像吗？</p>
          <p class="tips-text">建议使用正方形图片，文件大小不超过2MB</p>
        </div>
      </div>
    </dialog-box>

          <!-- 个人资料编辑对话框 -->
    <dialog-box
      title="编辑个人资料"
      :visible.sync="dialogVisible"
      width="600px"
      @confirm="updateUserInfo"
      @cancel="dialogVisible = false"
    >
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <div class="avatar-preview">
            <el-avatar :size="80" :src="editForm.avatar || defaultAvatar"></el-avatar>
            <upload-box v-model="editForm.avatar" :limit="1" accept="image/*">
              <button-box type="primary" text="上传头像" size="small"></button-box>
            </upload-box>
          </div>
        </el-form-item>
        <el-form-item label="个人标签">
          <tags-input 
            v-model="editForm.tags"
            placeholder="请输入标签后回车"
            :maxTags="5"
            addButtonText="添加个人标签">
          </tags-input>
          <div class="form-tips">最多添加5个标签，用于展示个人特长和兴趣</div>
        </el-form-item>

      </el-form>
    </dialog-box>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { changePasswordApi } from '@/api/user'
import validate from '@/utils/validate'

export default {
  name: 'UserProfile',
  data() {
    // 验证两次密码是否一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {

      // 用户详细信息
      userInfo: {
        username: '',
        name: '',
        email: '',
        phone: '',
        roles: [],
        avatar: '',
        tags: ['Vue.js', 'JavaScript', 'Element UI']
      },
      
      // 密码表单
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      
      // 密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          validate.password()
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      
      // 个人资料编辑表单
      dialogVisible: false,
      editForm: {
        name: '',
        email: '',
        avatar: '',
        phone: '',
        tags: []
      },
      
      // 编辑表单验证规则
      editRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          validate.required(),
          validate.email()
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      
      // 头像相关
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      
      // 标签相关
      tagTypes: ['', 'success', 'info', 'warning', 'danger'],

      // 头像上传相关
      avatarUploading: false,
      avatarUploadProgress: 0,

      // 头像预览相关
      avatarPreviewVisible: false,
      previewAvatarUrl: '',
      currentUploadFile: null
    }
  },
  computed: {
    ...mapGetters({
      roles: 'user/roles',
      avatar: 'user/avatar',
      name: 'user/name',
      canChangePassword: 'user/canChangePassword'
    }),
    
    // 上传请求头
    uploadHeaders() {
      const token = localStorage.getItem('Admin-Token')
      return token ? { Authorization: `Bearer ${token}` } : {}
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      // 在实际项目中应该从后端获取完整用户信息
      // 这里使用模拟数据和vuex中的部分数据
      this.userInfo = {
        username: 'admin',
        name: this.name,
        email: 'admin@example.com',
        phone: '13800138000',
        roles: this.roles,
        avatar: this.avatar,
        tags: ['Vue.js', 'JavaScript', 'Element UI']
      }
      
      // 初始化编辑表单
      this.editForm = {
        name: this.userInfo.name,
        email: this.userInfo.email,
        phone: this.userInfo.phone,
        avatar: this.userInfo.avatar,
        tags: [...this.userInfo.tags]
      }
    },
    
    // 头像上传相关方法
    handleAvatarSuccess(response, file) {
      this.avatarUploading = false
      this.avatarUploadProgress = 0
      
      // 处理真实的上传响应
      if (response && response.code === 200) {
        // 更新用户头像
        this.userInfo.avatar = response.data.url
        // 同时更新store中的头像
        this.$store.dispatch('user/updateUserInfo', {
          name: this.userInfo.name,
          avatar: response.data.url
        })
        this.$messageBox.success('头像上传成功')
      } else {
        this.$messageBox.error(response?.message || '头像上传失败')
      }
      
      // 清理状态
      this.currentUploadFile = null
      this.previewAvatarUrl = ''
      
      // 清除upload组件的文件
      if (this.$refs.avatarUpload) {
        this.$refs.avatarUpload.clearFiles()
      }
    },

    handleAvatarError(err, file, fileList) {
      this.avatarUploading = false
      this.avatarUploadProgress = 0
      console.error('头像上传错误:', err)
      this.$messageBox.error('头像上传失败，请重试')
      
      // 清理状态
      this.currentUploadFile = null
      this.previewAvatarUrl = ''
      
      // 清除upload组件的文件
      if (this.$refs.avatarUpload) {
        this.$refs.avatarUpload.clearFiles()
      }
    },

    handleAvatarProgress(event, file, fileList) {
      this.avatarUploadProgress = Math.round(event.percent)
    },
    
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      const isValidFormat = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
      
      if (!isImage) {
        this.$messageBox.error('上传头像只能是图片格式!')
        return false
      }
      
      if (!isValidFormat) {
        this.$messageBox.error('只支持 JPG、PNG、GIF 格式的图片!')
        return false
      }
      
      if (!isLt2M) {
        this.$messageBox.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      
      // 保存当前文件并显示预览
      this.currentUploadFile = file
      this.previewAvatarUrl = URL.createObjectURL(file)
      this.avatarPreviewVisible = true
      
      return false // 阻止自动上传，等待用户确认
    },

    // 模拟上传过程（仅用于开发环境）
    simulateUpload(file) {
      // 模拟上传进度
      const interval = setInterval(() => {
        this.avatarUploadProgress += 10
        if (this.avatarUploadProgress >= 100) {
          clearInterval(interval)
          // 模拟上传成功
          setTimeout(() => {
            const mockResponse = {
              code: 200,
              data: {
                url: URL.createObjectURL(file)
              },
              message: '上传成功'
            }
            this.handleAvatarSuccess(mockResponse, file)
          }, 300)
        }
      }, 100)
    },
    

    
    // 处理修改密码
    handleChangePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          // 显示加载
          this.$messageBox.loading('正在修改密码...')
          
          // 调用修改密码API
          changePasswordApi({
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          }).then(() => {
            this.$messageBox.success('密码修改成功')
            // 重置表单
            this.passwordForm = {
              oldPassword: '',
              newPassword: '',
              confirmPassword: ''
            }
            this.$refs.passwordForm.clearValidate()
          }).catch(error => {
            this.$messageBox.error(error.message || '密码修改失败')
          }).finally(() => {
            this.$messageBox.closeLoading()
          })
          
          // 模拟API调用
          setTimeout(() => {
            this.$messageBox.success('密码修改成功')
            // 重置表单
            this.passwordForm = {
              oldPassword: '',
              newPassword: '',
              confirmPassword: ''
            }
            this.$refs.passwordForm.clearValidate()
            this.$messageBox.closeLoading()
          }, 1000)
        }
      })
    },
    
    // 处理编辑个人资料
    handleEditInfo() {
      this.dialogVisible = true
    },

    // 打开头像预览对话框
    openAvatarPreview(avatarUrl) {
      this.previewAvatarUrl = avatarUrl;
      this.avatarPreviewVisible = true;
    },

    // 确认头像上传
    confirmAvatarUpload() {
      this.avatarPreviewVisible = false
      
      if (!this.currentUploadFile) {
        this.$messageBox.error('未选择文件')
        return
      }
      
      // 开始上传
      this.avatarUploading = true
      this.avatarUploadProgress = 0
      
      // 开发环境模拟上传
      if (process.env.NODE_ENV === 'development') {
        this.simulateUpload(this.currentUploadFile)
      } else {
        // 生产环境真实上传
        this.uploadAvatarToServer(this.currentUploadFile)
      }
    },

    // 真实上传到服务器
    uploadAvatarToServer(file) {
      const formData = new FormData()
      formData.append('file', file)
      
      this.$http.upload('/api/upload/avatar', file, {
        onUploadProgress: (progressEvent) => {
          this.avatarUploadProgress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
        }
      }).then(response => {
        this.handleAvatarSuccess(response, file)
      }).catch(error => {
        this.handleAvatarError(error, file)
      })
    },

    // 取消头像上传
    cancelAvatarUpload() {
      this.avatarPreviewVisible = false
      this.previewAvatarUrl = ''
      this.currentUploadFile = null
      
      // 清除upload组件的文件
      if (this.$refs.avatarUpload) {
        this.$refs.avatarUpload.clearFiles()
      }
    },
    
    // 更新用户信息
    updateUserInfo() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 显示加载
          this.$messageBox.loading('正在更新个人资料...')
          
          // 更新store中的用户信息
          this.$store.dispatch('user/updateUserInfo', {
            name: this.editForm.name,
            avatar: this.editForm.avatar
          }).then(() => {
            // 更新本地显示
            this.userInfo.name = this.editForm.name
            this.userInfo.email = this.editForm.email
            this.userInfo.phone = this.editForm.phone
            this.userInfo.avatar = this.editForm.avatar
            this.userInfo.tags = [...this.editForm.tags]
            
            // 关闭对话框
            this.dialogVisible = false
            this.$messageBox.success('个人资料更新成功')
          }).catch(error => {
            this.$messageBox.error(error.message || '更新失败')
          }).finally(() => {
            this.$messageBox.closeLoading()
          })
          
          // 模拟API调用
          setTimeout(() => {
            // 更新本地显示
            this.userInfo.name = this.editForm.name
            this.userInfo.email = this.editForm.email
            this.userInfo.phone = this.editForm.phone
            this.userInfo.avatar = this.editForm.avatar
            this.userInfo.tags = [...this.editForm.tags]
            
            // 关闭对话框
            this.dialogVisible = false
            this.$messageBox.success('个人资料更新成功')
            this.$messageBox.closeLoading()
          }, 1000)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-profile {
  padding: 20px;
  
  .box-card {
    margin-bottom: 20px;
  }
  
  .user-info {
    display: flex;
    
    .avatar-container {
      margin-right: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .avatar-upload {
        margin-top: 10px;
        width: 100px;
        
        .upload-progress {
          margin-top: 8px;
          width: 100%;
        }
      }
    }
    
    .info-container {
      flex: 1;
      
      .info-item {
        margin-bottom: 15px;
        display: flex;
        
        .label {
          font-weight: bold;
          width: 80px;
        }
        
        .value {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          
          .text-muted {
            color: #909399;
            font-size: 14px;
          }
        }
      }
    }
  }
  
  .no-permission {
    text-align: center;
    padding: 30px;
    color: #909399;
    
    i {
      font-size: 40px;
      margin-bottom: 10px;
    }
  }
  
  .avatar-preview {
    display: flex;
    align-items: center;
    
    .el-avatar {
      margin-right: 20px;
    }
  }

  .avatar-preview-container {
    text-align: center;

    .preview-image {
      margin-bottom: 15px;
      img {
        max-width: 100%;
        max-height: 200px;
        border-radius: 4px;
      }
    }

    .preview-tips {
      color: #909399;
      font-size: 14px;
      p {
        margin-bottom: 5px;
      }
      .tips-text {
        font-size: 12px;
      }
    }
  }
  
  .form-tips {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}
</style> 